package com.tourism.www.common.page;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import lombok.NoArgsConstructor;

import java.util.Arrays;
import java.util.Optional;

@NoArgsConstructor
public class Condition {
    public static <T> IPage<T> getPage(PageQuery pageQuery) {
        Page<T> page = new Page<>(
                (long)Optional.ofNullable(pageQuery.getCurrent()).orElse(1),
                (long)Optional.ofNullable(pageQuery.getSize()).orElse(10)
        );

        if (pageQuery.getAsc() != null) {
            Arrays.stream(TypeUtil.toStrArray(pageQuery.getAsc())).forEach((asc) -> {
                page.addOrder(OrderItem.asc(asc));
            });
        } else if (pageQuery.getDesc() != null) {
            Arrays.stream(TypeUtil.toStrArray(pageQuery.getDesc())).forEach((desc) -> {
                page.addOrder(OrderItem.desc(desc));
            });
        }
        return page;
    }

    public static <T> QueryWrapper<T> getQueryWrapper(T entity) {
        return new QueryWrapper<>(entity);
    }
}
